{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1ce74ea3",
   "metadata": {},
   "source": [
    "# 模块和包"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8a463ae6",
   "metadata": {},
   "source": [
    "## 模块\n",
    "\n",
    "Python会将所有 .py 结尾的文件认定为Python代码文件。\n",
    "\n",
    "考虑这样一个脚本文件 `ex1.py`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8eca712e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Writing ex1.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile ex1.py\n",
    "PI = 3.1416\n",
    "\n",
    "def sum(lst):\n",
    "    tot = lst[0]\n",
    "    for value in lst[1:]:\n",
    "        tot = tot + value\n",
    "    return tot\n",
    "    \n",
    "w = [0, 1, 2, 3]\n",
    "print(sum(w), PI)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e71ad94",
   "metadata": {},
   "source": [
    "执行这个脚本："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3241f63a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 3.1416\r\n"
     ]
    }
   ],
   "source": [
    "!python ex1.py"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d5d6b40",
   "metadata": {},
   "source": [
    "为了复用代码，Python可以将这个脚本当作一个模块，使用 import 关键词加载并执行它（这里要求ex1.py在当前工作目录）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5d3b773a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6 3.1416\n"
     ]
    }
   ],
   "source": [
    "import ex1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8f39b69e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "module"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(ex1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "b49bb687",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<module 'ex1' from '/Users/lijin/Documents/Projects/notes-python3/ch02-Python基础/ex1.py'>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ex1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7943fb8f",
   "metadata": {},
   "source": [
    "在导入时，Python会执行一遍模块中的所有内容，所以print()函数的结果被输出了。\n",
    "\n",
    "ex1.py 中所有的变量都被载入了当前环境中，不过要使用`ex1.变量名`的方法来查看或者修改这些变量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "9ef8a5fc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.1416"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ex1.PI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "9c704fa5",
   "metadata": {},
   "outputs": [],
   "source": [
    "ex1.PI = 3.141592653"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d66be72f",
   "metadata": {},
   "source": [
    "还可以用`ex1.函数名`调用模块里面的函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "3824e431",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ex1.sum([2, 3, 4, 5])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bd55983",
   "metadata": {},
   "source": [
    "为了提高效率，Python只会载入模块一次，已经载入的模块再次载入时，Python并不会真正执行载入操作，哪怕模块的内容已经改变："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "25025c2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fa6694b",
   "metadata": {},
   "source": [
    "删除示例文件："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "6a64c5e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "%rm ex1.py"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8c60ef4",
   "metadata": {},
   "source": [
    "## __name__ 属性\n",
    "\n",
    "有时候想将一个 .py 文件既当作脚本，又能当作模块用，这个时候可以使用 `.__name__` 这个属性。\n",
    "\n",
    "只有当文件被当作脚本执行的时候， `__name__`的值才会是 `'__main__'`，所以可以这样定义脚本："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "eab38a2f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting ex2.py\n"
     ]
    }
   ],
   "source": [
    "%%writefile ex2.py\n",
    "PI = 3.1416\n",
    "\n",
    "def sum(lst):\n",
    "    \"\"\" Sum the values in a list\n",
    "    \"\"\"\n",
    "    tot = 0\n",
    "    for value in lst:\n",
    "        tot = tot + value\n",
    "    return tot\n",
    "\n",
    "def add(x, y):\n",
    "    \" Add two values.\"\n",
    "    a = x + y\n",
    "    return a\n",
    "\n",
    "def test():\n",
    "    w = [0,1,2,3]\n",
    "    assert(sum(w) == 6)\n",
    "    print('test passed.')\n",
    "    \n",
    "if __name__ == '__main__':\n",
    "    test()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9fc8e960",
   "metadata": {},
   "source": [
    "运行文件："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "032f596f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test passed.\r\n"
     ]
    }
   ],
   "source": [
    "!python ex2.py"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "653214ed",
   "metadata": {},
   "source": [
    "当作模块导入， test() 不会执行："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "cfed264e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ex2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f428e3d1",
   "metadata": {},
   "source": [
    "可以使用其中的变量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "6c3b5d92",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.1416"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ex2.PI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73d7359c",
   "metadata": {},
   "source": [
    "## 其他导入方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "71c3bbb8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.1416"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import ex2 as e2\n",
    "\n",
    "e2.PI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "cca36ae0",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ex2 import add, PI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17ccef3c",
   "metadata": {},
   "source": [
    "使用 from 后，可以直接使用 add ， PI："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c71af568",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.1416"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add(2, PI)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "78658d23",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ex2 import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "344b2098",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.5"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "add(3, 4.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39afa990",
   "metadata": {},
   "source": [
    "这种导入方法不是很提倡，因为如果你不确定导入的都有哪些，可能覆盖一些已有的函数。\n",
    "\n",
    "删除示例文件："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "28687cf6",
   "metadata": {},
   "outputs": [],
   "source": [
    "%rm ex2.py"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f8b9b9f",
   "metadata": {},
   "source": [
    "## 包\n",
    "\n",
    "有这样的一个文件夹foo：\n",
    "\n",
    "```\n",
    "foo/\n",
    "\n",
    "__init__.py\n",
    "bar.py (defines func)\n",
    "baz.py (defines zap)\n",
    "``\n",
    "\n",
    "在Python中，这样的文件夹 foo 是一个包，可以这样导入其中的内容：\n",
    "\n",
    "```python\n",
    "from foo.bar import func\n",
    "from foo.baz import zap\n",
    "```\n",
    "\n",
    "其中bar 和 baz 都是 foo 文件夹下的 .py 文件。\n",
    "\n",
    "导入包要求：\n",
    "\n",
    "- 文件夹 foo 在Python的搜索路径中\n",
    "- 要有`__init__.py`，它可以是个空文件。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
